<template>
  <div class="ssc-list org-position-list">
    <div class="ssc-search">
      <a-form :model="searchParam" autocomplete="off">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="工单类型">
              <a-select v-model:value="searchParam.worksheetType" placeholder="请选择类型" allowClear :options="worksheetTypeOptions" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="业务范围">
              <a-input v-model:value="searchParam.businessScope" placeholder="请输入业务范围" allowClear />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-row justify="end">
              <a-button @click="clear()">重置</a-button>
              <a-button class="ml-4" type="primary" @click="search()">查询</a-button>
            </a-row>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="ssc-table">
      <div class="ssc-table-header">
        <span class="ssc-table-header-title">工单类型维护</span>
        <a-button type="primary" @click="add()">
          <template #icon><plus-outlined :style="{ 'font-weight': 'bold' }" /></template>
          定义新工单
        </a-button>
      </div>
      <a-table :columns="columns" :data-source="dataList" :loading="loading" :pagination="pagination" @change="onPaginationChange">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'approveTime'">
            <span>{{ record.approveTime ? formatToDateTime(record.approveTime) : '--' }}</span>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <span>
              <a @click="changeState(record)">{{ record.worksheetState === 1 ? '停用' : '恢复使用' }}</a>
              <a-divider type="vertical" />
              <a @click="toFormSettings(record)">工单表单</a>
              <a-divider type="vertical" />
              <a @click="toProcess">处理流程</a>
            </span>
          </template>
        </template>
      </a-table>
    </div>
    <Add v-model:visible="modalAdd.visible" @success="modalAdd.success" />
  </div>
</template>

<script lang="ts" setup>
  import { PlusOutlined } from '@ant-design/icons-vue'
  // import type { SelectProps } from 'ant-design-vue'
  // import { message } from 'ant-design-vue'
  import { onMounted, reactive, ref } from 'vue'
  import { useRouter } from 'vue-router'

  import { requestGetBusinessDic, requestGetWorksheetListByPage, requestUpdateWorksheet } from '/@/api/business/worksheet'
  import { ApplicationScopeDesc } from '/@/api/business/worksheet/enum'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { useQueryPagination } from '/@/hooks/useQueryPagination'
  import { formatToDateTime } from '/@/utils/date'

  import Add from './components/Add.vue'
  const router = useRouter()
  /** 搜索条件 */
  const searchParam = reactive({
    worksheetType: null,
    businessScope: '',
  })

  /** 类型选项 */
  // const worksheetTypeOptions = ref<SelectProps['options']>(Object.entries(WorksheetTypeDesc).map((item) => ({ label: item[1], value: parseInt(item[0]) })))
  const worksheetTypeOptions = ref([])
  const getBusinessDic = async () => {
    const { responseCode, responseData } = await requestGetBusinessDic({ code: 'ws_type' })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      worksheetTypeOptions.value = responseData.map((item) => ({ label: item.describe, value: item.value }))
    }
  }
  getBusinessDic()

  /** 表格列配置 */
  const columns = [
    {
      title: '工单类型',
      dataIndex: 'worksheetType',
      customRender: ({ record }) => {
        const worksheetType = (worksheetTypeOptions.value || []).filter((item: any) => item.value == record.worksheetType)
        return worksheetType.length ? worksheetType[0].label : ''
      },
    },
    {
      title: '适用范围',
      dataIndex: 'applicationScope',
      customRender: ({ record }) => {
        const applicationScope = record.applicationScope.split(',')
        let scopeString = ''
        applicationScope.forEach((item, index) => {
          scopeString += `${index !== 0 ? ',' : ''}${ApplicationScopeDesc[item]}`
        })
        return scopeString
      },
    },
    { title: '业务范围', dataIndex: 'businessScope' },
    {
      title: '状态',
      dataIndex: 'worksheetState',
      customRender: ({ record }) => {
        return record.worksheetState === 1 ? '有效' : '停用'
      },
    },
    { title: '操作', dataIndex: 'action' },
  ]
  /** 新增弹窗 */
  const modalAdd = reactive({
    visible: false,
    success: () => queryList(),
  })
  const add = async () => {
    modalAdd.visible = true
  }

  const toFormSettings = (record) => {
    router.push({
      path: `/orderMaintenance/type/form-settings`,
      query: { paperId: record.paperId },
    })
  }
  const toProcess = () => {
    router.push({
      path: `/orderMaintenance/type/process-config`,
    })
  }
  const changeState = async (record) => {
    const { responseCode } = await requestUpdateWorksheet({
      id: record.id,
      worksheetState: record.worksheetState === 1 ? 2 : 1, // 工单状态 1使用 2停用
    })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      // message.success('添加成功')
      queryList()
    }
  }
  const { loading, queryList, dataList, pagination, onPaginationChange } = useQueryPagination<GetWorksheetListByPage.IRequest, GetWorksheetListByPage.IResponse[]>(searchParam, requestGetWorksheetListByPage)

  onMounted(() => {
    search()
  })

  /**
   * 重置
   */
  const clear = () => {
    searchParam.worksheetType = null
    searchParam.businessScope = ''
    search()
  }

  /**
   * 搜索
   */
  const search = async () => queryList({ current: 1 })
</script>

<style lang="less" scoped></style>
